import { Button, Message, Radio, Select, Switch } from '@kedacom/react-next'
import { t } from 'i18next'
import React, { useEffect } from 'react'
import shallow from 'zustand/shallow'
import CreateMember from '../../components/CreateMember'
import { useBasicInfoStore } from '../basicInfo/store'
import { useMeetingMixStore } from './store'
import { StyledMixSelectItem, StyledWrap } from './style'
import { useCreateContentStore } from '../../store'
import { fetchDelMix, fetchMixDetail, fetchSaveMix, fetchUpdateMix } from '@/api/create/mix'
import { useMeetingParamsStore } from '../meetingParams/store'
import Alert, { Confirm } from '@/components/Alert'
import { setMixList } from '../../store.combine'
import { useKdPreSettingDialogStore } from '../../components/KdPreSettingDialog/store'
import LabelWrap from '../../components/LabelWrap'

export default function MeetingMix() {
	const { init, planOptions, enable, update, mode, members, name, planValue, loadPlanData, getMixData } =
		useMeetingMixStore(
			(state) => ({
				members: state.members,
				init: state.init,
				enable: state.enable,
				mode: state.mode,
				update: state.update,
				planOptions: state.planOptions,
				loadPlanData: state.loadPlanData,
				planValue: state.planValue,
				name: state.name,
				getMixData: state.getMixData,
			}),
			shallow
		)
	const repeat = useBasicInfoStore((state) => state.repeat)

	useEffect(() => {
		update({ planValue: planOptions.find((item) => item.label === name)?.value ?? '0' })
	}, [planOptions, name])

	const changeMode = (_mode: number) => {
		if (_mode === 2) {
			//选中定制混音
			if (useMeetingParamsStore.getState().voiceInspireEnable) {
				Alert(t('定制混音和语音激励不能同时开启，请先关闭语音激励'))
				return false
			}
			update({ mode: _mode })
			return true
		} else {
			update({ mode: _mode })
			return true
		}
	}

	const getMixDetail = async (id: string) => {
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const res = await fetchMixDetail(isTemplate, preKey, id)
		if (res.success) {
			if (res && res.mode === 2 && useMeetingParamsStore.getState().voiceInspireEnable) {
				Alert(t('定制混音和语音激励不能同时开启，请先关闭语音激励'))
				return
			}
			init(res ?? null)
		} else {
			init(null)
		}
	}

	const changePlan = (_d: string) => {
		const item = planOptions.find((item) => item.value === _d)
		update({ planValue: _d, name: item?.label, members: [], mode: 1 })
		if (_d === '0') {
			update({ enable: true, tDefault: 0, planValue: '0' })
		} else {
			getMixDetail(_d)
		}
	}

	const updatePlan = async (name: string, data: { label: string; value: string }) => {
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const params = Object.assign({}, getMixData(repeat), { name: name })
		const res = await fetchUpdateMix(isTemplate, preKey, data?.value || '', params)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name })
			loadPlanData()
		} else {
			Alert(res.description)
		}
	}
	const savePlan = async (name: string) => {
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const params = Object.assign({}, getMixData(repeat), { name: name })
		const res = await fetchSaveMix(isTemplate, preKey, params)
		if (res.success) {
			Message.info(t('预案保存成功'))
			update({ name: name })
			loadPlanData()
		} else {
			Alert(res.description)
		}
	}

	const deletePlan = async (item: { label: string; value: string }) => {
		let _plan_option = planOptions.filter((v) => item.value !== v.value)
		const isTemplate = useCreateContentStore.getState().isTemplate
		const preKey = useCreateContentStore.getState().preKey

		Confirm(t('是否确定删除{{name}}？', { name: item.label }), async () => {
			const res = await fetchDelMix(isTemplate, preKey, item.value)
			if (res.success) {
				update({ name: t('不使用预案'), planOptions: _plan_option, planValue: '0' })
			} else {
				Alert(res.description)
			}
		})
	}

	const openDialog = () => {
		if (!enable) {
			return false
		}
		if (mode === 2 && members.length === 0 /**定制混音 列表不能为空 */) {
			Alert(t('混音列表不能为空'))
			return false
		}
		const preKey = useCreateContentStore.getState().preKey
		const isTemplate = useCreateContentStore.getState().isTemplate
		const url = isTemplate ? `/meetings/${preKey}/premixs?count=0` : `/personal_templates/${preKey}/premixs?count=0`

		let _name = name
		if (planValue === '0') {
			update({ name: '' })
			_name = ''
		}
		useKdPreSettingDialogStore.setState({
			isOpen: true,
			dialogTitle: t('保存为预案'),
			loadUrl: url,
			name: _name,
			type: 'mix',
			self_save: savePlan,
			self_over: updatePlan,
		})
	}

	return (
		<StyledWrap className="mix">
			<LabelWrap label={t('混音', { context: 'SC1' })}>
				<Switch
					width={40}
					height={22}
					className="video"
					checked={enable}
					onChange={(e, v) => {
						update({ enable: v })
					}}
				></Switch>
			</LabelWrap>

			{enable && !repeat && (
				<LabelWrap label={t('混音预案')}>
					<Select
						options={planOptions}
						value={planValue}
						onClick={(e, v) => changePlan(v)}
						optionRender={(option, selected) => (
							<StyledMixSelectItem className={selected ? 'selected' : ''}>
								<span className="select-icon"></span>
								<span className="text" title={option.label}>
									{option.label}
								</span>
								{option.value !== '0' && (
									<span
										className="delete-icon"
										onClick={(e) => {
											e.stopPropagation()
											deletePlan(option as { label: string; value: string })
										}}
									>
										×
									</span>
								)}
							</StyledMixSelectItem>
						)}
					/>
					<Button onClick={openDialog} style={{ margin: '0 0 0 10px' }}>
						{t('保存预案')}
					</Button>
				</LabelWrap>
			)}
			{enable && (
				<LabelWrap label={t('混音')} className="mix-mode__i18n">
					<Radio
						checked={mode === 1}
						onChange={() => {
							changeMode(1)
						}}
						width={120}
					>
						{t('智能混音', { context: 'SC1' })}
					</Radio>
					<Radio
						checked={mode === 2}
						onChange={() => {
							changeMode(2)
						}}
						width={120}
					>
						{t('定制混音', { context: 'SC1' })}
					</Radio>
				</LabelWrap>
			)}
			{enable && mode === 2 && (
				<CreateMember
					title={t('已选')}
					width={540}
					height={320}
					list={members}
					setOuterList={(h, type) => {
						if (type === 'drop') {
							setMixList(h)
						} else {
							update({ members: h })
						}
					}}
					isShowBottomTip={false}
					isHideOrder={true}
				></CreateMember>
			)}
		</StyledWrap>
	)
}
